<template>
  <div class="chart-and-data-container">
    <!-- 左侧图表容器 -->
    <div class="chart-container">
      <div class="chart-header">
        <h3>每时用户行为趋势分析</h3>
        <div class="controls">
          <div class="chart-type-selector">
            <label>图表类型：</label>
            <select v-model="chartType" @change="initChart">
              <option value="bar">分组柱状图</option>
              <option value="stackedBar">堆叠柱状图</option>
            </select>
          </div>
        </div>
      </div>
      <div ref="chart" class="chart-inner"></div>
    </div>
    
    <!-- 右侧数据表格容器 -->
    <div class="data-table-container">
      <h3>每时数据明细</h3>
      <div class="table-scroll-wrapper">
        <table v-if="hourlyTableData.length > 0" class="data-table">
          <thead>
            <tr>
              <th>时间段</th>
              <th>用户数</th>
              <th>浏览量</th>
              <th>收藏量</th>
              <th>加购量</th>
              <th>购买量</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in hourlyTableData" :key="index">
              <td>{{ item.hourLabel }}</td>
              <td>{{ item.userCnt }}</td>
              <td>{{ item.pvCnt }}</td>
              <td>{{ item.favCnt }}</td>
              <td>{{ item.cartCnt }}</td>
              <td>{{ item.buyCnt }}</td>
            </tr>
            <tr class="total-row">
              <td><strong>总计</strong></td>
              <td><strong>{{ totalUserCnt }}</strong></td>
              <td><strong>{{ totalPvCnt }}</strong></td>
              <td><strong>{{ totalFavCnt }}</strong></td>
              <td><strong>{{ totalCartCnt }}</strong></td>
              <td><strong>{{ totalBuyCnt }}</strong></td>
            </tr>
          </tbody>
        </table>
        <p v-else class="no-data">暂无数据</p>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { onMounted, ref, watch, onUnmounted, computed } from 'vue';

export default {
  name: 'HourlyTrend',
  props: {
    chartData: {
      type: Array,
      default: () => []
    }
  },
  setup(props) {
    const chart = ref(null);
    let myChart = null;
    const chartType = ref('bar'); // 默认分组柱状图

    // 处理每时数据，按小时排序
    const hourlyData = computed(() => {
      if (!props.chartData || props.chartData.length === 0) return [];
      
      // 深拷贝数据并排序
      const sortedData = [...props.chartData].sort((a, b) => a.hour - b.hour);
      
      // 转换为需要的格式，确保24小时数据完整
      const hourStats = {};
      
      // 初始化24小时的数据
      for (let i = 0; i < 24; i++) {
        const hourLabel = `${i.toString().padStart(2, '0')}:00`;
        hourStats[i] = {
          hour: i,
          hourLabel: hourLabel,
          userCnt: 0,
          pvCnt: 0,
          favCnt: 0,
          cartCnt: 0,
          buyCnt: 0
        };
      }
      
      // 填充实际数据
      sortedData.forEach(item => {
        if (item.hour !== undefined && item.hour >= 0 && item.hour < 24) {
          hourStats[item.hour] = {
            hour: item.hour,
            hourLabel: `${item.hour.toString().padStart(2, '0')}:00`,
            userCnt: item.userCnt || 0,
            pvCnt: item.pvCnt || 0,
            favCnt: item.favCnt || 0,
            cartCnt: item.cartCnt || 0,
            buyCnt: item.buyCnt || 0
          };
        }
      });
      
      // 转换为数组
      return Object.values(hourStats);
    });

    // 表格数据（与图表数据相同）
    const hourlyTableData = computed(() => {
      return hourlyData.value;
    });

    // 计算总计
    const totalUserCnt = computed(() => {
      return hourlyTableData.value.reduce((sum, item) => sum + item.userCnt, 0);
    });

    const totalPvCnt = computed(() => {
      return hourlyTableData.value.reduce((sum, item) => sum + item.pvCnt, 0);
    });

    const totalFavCnt = computed(() => {
      return hourlyTableData.value.reduce((sum, item) => sum + item.favCnt, 0);
    });

    const totalCartCnt = computed(() => {
      return hourlyTableData.value.reduce((sum, item) => sum + item.cartCnt, 0);
    });

    const totalBuyCnt = computed(() => {
      return hourlyTableData.value.reduce((sum, item) => sum + item.buyCnt, 0);
    });

    const initChart = () => {
      if (!chart.value) return;
      
      // 销毁旧的图表实例（如果存在）
      if (myChart) {
        myChart.dispose();
      }
      
      myChart = echarts.init(chart.value);
      
      const data = hourlyData.value;
      
      // 如果没有数据，显示提示
      if (data.length === 0) {
        myChart.setOption({
          title: {
            text: '暂无数据',
            left: 'center',
            top: 'center'
          }
        });
        return;
      }
      
      // 提取小时标签和各类数据
      const hourLabels = data.map(item => item.hourLabel);
      const userCntData = data.map(item => item.userCnt);
      const pvData = data.map(item => item.pvCnt);
      const favData = data.map(item => item.favCnt);
      const cartData = data.map(item => item.cartCnt);
      const buyData = data.map(item => item.buyCnt);
      
      // 获取容器宽度用于响应式调整
      const { offsetWidth } = chart.value;
      
      // 根据选择的图表类型配置系列
      let series = [];
      
      if (chartType.value === 'bar') {
        // 分组柱状图配置
        series = [
          {
            name: '用户数',
            type: 'bar',
            data: userCntData,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#5470c6' },
                { offset: 1, color: '#83bff6' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: '#5470c6'
              }
            }
          },
          {
            name: '浏览量',
            type: 'bar',
            data: pvData,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#91cc75' },
                { offset: 1, color: '#95de64' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: '#91cc75'
              }
            }
          },
          {
            name: '收藏量',
            type: 'bar',
            data: favData,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#fac858' },
                { offset: 1, color: '#ffd666' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: '#fac858'
              }
            }
          },
          {
            name: '加购量',
            type: 'bar',
            data: cartData,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#ee6666' },
                { offset: 1, color: '#ff9c6e' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: '#ee6666'
              }
            }
          },
          {
            name: '购买量',
            type: 'bar',
            data: buyData,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#73c0de' },
                { offset: 1, color: '#3ba272' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: '#73c0de'
              }
            }
          }
        ];
      } else if (chartType.value === 'stackedBar') {
        // 堆叠柱状图配置
        series = [
          {
            name: '用户数',
            type: 'bar',
            stack: 'total',
            data: userCntData,
            itemStyle: { color: '#5470c6' },
            emphasis: { focus: 'series' }
          },
          {
            name: '浏览量',
            type: 'bar',
            stack: 'total',
            data: pvData,
            itemStyle: { color: '#91cc75' },
            emphasis: { focus: 'series' }
          },
          {
            name: '收藏量',
            type: 'bar',
            stack: 'total',
            data: favData,
            itemStyle: { color: '#fac858' },
            emphasis: { focus: 'series' }
          },
          {
            name: '加购量',
            type: 'bar',
            stack: 'total',
            data: cartData,
            itemStyle: { color: '#ee6666' },
            emphasis: { focus: 'series' }
          },
          {
            name: '购买量',
            type: 'bar',
            stack: 'total',
            data: buyData,
            itemStyle: { color: '#73c0de' },
            emphasis: { focus: 'series' }
          }
        ];
      }
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        toolbox: {
          feature: {
            saveAsImage: {
              title: '保存图片',
              type: 'png'
            }
          },
          right: 10,
          top: 10
        },
        legend: {
          data: ['用户数', '浏览量', '收藏量', '加购量', '购买量'],
          bottom: 10
        },
        grid: {
          left: offsetWidth < 600 ? '10%' : '5%',
          right: offsetWidth < 600 ? '10%' : '5%',
          bottom: '15%',
          top: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: hourLabels,
          axisLabel: {
            rotate: 45,
            fontSize: offsetWidth < 600 ? 10 : 12
          },
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          name: '数量',
          min: 0,
          axisLabel: {
            formatter: '{value}'
          }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100
          }
        ],
        series: series
      };
      
      myChart.setOption(option);
    };

    const handleResize = () => {
      if (myChart) {
        myChart.resize();
      }
    };

    onMounted(() => {
      window.addEventListener('resize', handleResize);
      // 添加延迟确保DOM完全渲染
      setTimeout(() => {
        initChart();
      }, 100);
    });

    onUnmounted(() => {
      window.removeEventListener('resize', handleResize);
      if (myChart) {
        myChart.dispose();
      }
    });

    watch(() => props.chartData, () => {
      if (myChart) {
        setTimeout(() => {
          initChart();
        }, 50);
      }
    }, { deep: true });

    // 监听图表类型的变化
    watch(chartType, () => {
      if (myChart) {
        setTimeout(() => {
          initChart();
        }, 50);
      }
    });

    return {
      chart,
      chartType,
      hourlyTableData,
      totalUserCnt,
      totalPvCnt,
      totalFavCnt,
      totalCartCnt,
      totalBuyCnt,
      initChart
    };
  }
}
</script>

<style scoped>
.chart-and-data-container {
  display: flex;
  width: 100%;
  gap: 20px;
  height: 100%; /* 填充父容器高度 */
}

.chart-container {
  flex: 3;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 15px;
}

.chart-header h3 {
  margin: 0;
  color: #333;
  flex-shrink: 0;
}

.controls {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.chart-type-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chart-type-selector label {
  font-weight: bold;
  color: #666;
  white-space: nowrap;
}

.chart-type-selector select {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #fff;
  min-width: 120px;
}

/* 图表内部容器，确保占满可用空间 */
.chart-inner {
  width: 100%;
  height: 100%;  /* 使用固定高度百分比 */
  min-height: 400px; /* 最小高度保障 */
}

.data-table-container {
  flex: 1;
  min-width: 300px;
  height: 100%;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.data-table-container h3 {
  margin-top: 0;
  margin-bottom: 15px;
  text-align: center;
  color: #333;
}

.table-scroll-wrapper {
  overflow-x: auto;
  overflow-y: auto;
  flex: 1;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
}

.data-table th,
.data-table td {
  border: 1px solid #eaeaea;
  padding: 6px 8px;
  text-align: center;
}

.data-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
  position: sticky;
  top: 0;
}

.data-table tr:hover {
  background-color: #f5f7fa;
}

.total-row {
  background-color: #e6f7ff;
  font-weight: bold;
}

.total-row td {
  border-top: 2px solid #1890ff;
}

.no-data {
  text-align: center;
  color: #999;
  margin: 20px 0;
}

/* 响应式布局 */
@media (max-width: 968px) {
  .chart-and-data-container {
    flex-direction: column;
  }
  
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .controls {
    flex-direction: column;
    gap: 10px;
    width: 100%;
  }
  
  .chart-type-selector {
    width: 100%;
  }
  
  .chart-type-selector select {
    flex-grow: 1;
  }
}
</style>